import 'dart:async';
import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:interview_flutter/hydra/service/interview_service.dart';
import 'package:interview_flutter/hydra/service/report_service.dart';
import 'package:interview_flutter/pages/interview/detail/StartInterviewSourceTracker.dart';
import 'package:interview_flutter/route/app_router.dart';
import 'package:interview_flutter/utils/KLog.dart';
import 'package:interview_flutter/utils/StringExt.dart';
import 'package:lottie/lottie.dart';

import '../../../manager/InterviewConfig.dart';
import '../../../model/interview/interview_detail_model.dart';
import '../../../provider/notifier/interview/interview_detail_notifier.dart';
import '../../../utils/page_utils.dart';
import '../../../widget/asset_image_3x.dart';
import '../../../widget/chat_bubble.dart';
import '../../../widget/videostack/dynamic_video_player_stack.dart';
import '../../../widget/videostack/player_factory.dart';
import '../dialog/call_error_dialog.dart';
import '../dialog/end_interview_dialog.dart';
import '../dialog/task_tip_card_dialog.dart';

@RoutePage()
class InterviewDetailsPage extends ConsumerStatefulWidget {
  const InterviewDetailsPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => InterviewDetailsState();
}

class InterviewDetailsState extends ConsumerState<InterviewDetailsPage> with TickerProviderStateMixin {
  final ScrollController _chatScrollController = ScrollController();
  late AnimationController _lottieController; // 添加控制器
  bool isPlayNormalVideoUrl = true;
  bool isShowCardDialog = false;
  late final DynamicVideoPlayerController _videoController;

  @override
  void initState() {
    super.initState();
    print("InterviewDetailsPage initState===");

    final sourceInfo = StartInterviewSourceTracker().getSourceInfo();
    ReportService.reportBlast("start_interview_click", sourceInfo);
    StartInterviewSourceTracker().clearSource();

    _lottieController = AnimationController(vsync: this); // 设置动画时长
    _videoController = DynamicVideoPlayerController(ref);
    InterviewService.curentContext = context;
  }

  @override
  void dispose() {
    _chatScrollController.dispose();
    _lottieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;

    final statusBarHeight = MediaQuery.of(context).padding.top;
    final isCreateRTCRoomSuccess = ref.watch(interviewDetailProvider).isCreateRTCRoomSuccess;
    final lottieState = ref.watch(lottieAnimationProvider);
    final lottieNotifier = ref.read(lottieAnimationProvider.notifier);
    final interviewDetail = ref.read(interviewDetailProvider.notifier);
    // 监听呼叫错误弹窗
    ref.listen<CallErrorDialogInfo?>(callErrorDialogProvider, (previousState, newState) {
      if (newState != null) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (dialogContext) => CallErrorDialogContent(),
        ).then((_) {
          ref.read(callErrorDialogProvider.notifier).state = null;
        });
      }
    });

    ref.listen<bool>(interviewDetailProvider.select((s) => s.isShowBottomBar), (previous, isVisible) {
      // 当底部栏变为可见时
      if (isVisible) {
        // 底部栏的动画时长是 200ms。我们稍作延迟以确保动画完成且UI已更新。
        Future.delayed(const Duration(milliseconds: 250), () {
          // 检查组件是否仍然挂载，并且滚动控制器已附加到ListView
          if (mounted && _chatScrollController.hasClients) {
            _chatScrollController.animateTo(
              _chatScrollController.position.maxScrollExtent,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut,
            );
          }
        });
      }
    });

    // 监听 AI 流式输出状态，控制 Lottie 动画
    ref.listen<InterviewDetailModel>(interviewDetailProvider, (previous, model) {
      final isAiSpeaking = model.isAISpeedSay;
      final definite = model.definite;
      if (isAiSpeaking) {
        if (definite) {
          if (!isPlayNormalVideoUrl) {
            isPlayNormalVideoUrl = true;
            KLog.i("RtcSdkService", "AI讲完了");
            _videoController.switchPlayer("normal_video");
            lottieNotifier.setAnimation(LottieState.end, loop: false, duration: const Duration(milliseconds: 166));
          }
        } else {
          if (isPlayNormalVideoUrl) {
            isPlayNormalVideoUrl = false;
            KLog.i("RtcSdkService", "AI开始讲");
            _videoController.switchPlayer("talking_video");
            lottieNotifier.setAnimation(LottieState.start, loop: false, duration: const Duration(milliseconds: 166));
          }
        }
      }
      if (model.isFinishInterview) {
        interviewDetail.resetFinishInterview();
        final pageTime = interviewDetail.seconds;
        final interviewType = interviewDetail.interviewType == 0 ? "求职面试" : "雅思面试";
        ReportService.reportBlast("complete_interview_show", {
          "Interview_Type": interviewType,
          "Interview_Time": pageTime,
        });
        showCongratulationsDialog(context, () {
          _routeToFeedbackGenerating(context, ref);
        });
      }
      if (model.isInterruptInterview) {
        interviewDetail.resetInterruptInterview();
        ref.read(interviewDetailProvider.notifier).leaveRoom(isRollback: true);
        showInterruptInterviewDialog(context, () {
          PageUtils.navigateToHomeAndRemoveOthers(context.router);
        });
      }
      if (model.showCardMsg) {
        if (!isShowCardDialog) {
          isShowCardDialog = true;
          showTaskTipCardDialog(
            context: context,
            onButtonPressed: () async {
              final ieltsCardText = ref.watch(interviewDetailProvider).ieltsCardText;
              final result = await context.router.push(TaskCardDetailRoute(ieltsCardText: ieltsCardText));
              if (result is bool) {
                print("===重新推流===");
                interviewDetail.publishStream();
                interviewDetail.resetShowCardMsg();
                isShowCardDialog = false;
              }
            },
          );
        }
      }
    });

    final double animTop = (screenWidth) * (1036.0 / 750.0) - 87;

    final videoSources = [
      VideoSource(
        id: "normal_video",
        primaryUrl: InterviewConfig.instance.realNormalVideoUrl,
        backupUrl: InterviewConfig.instance.realErrorNormalUrl,
      ),
      VideoSource(
        id: "talking_video",
        primaryUrl: InterviewConfig.instance.realTalkVideoUrl,
        backupUrl: InterviewConfig.instance.realErrorTalkUrl,
      ),
    ];
    // 只保留 primaryUrl 不为空的源
    final validSources = videoSources.where((s) => s.primaryUrl.isNotEmpty).toList();

    return WillPopScope(
      child: Scaffold(
        backgroundColor: "#F7F7F7".parseColor(),
        resizeToAvoidBottomInset: false,
        body: SafeArea(
          top: false,
          bottom: Platform.isAndroid ? true : false,
          child: Stack(
            children: [
              // 背景图
              assetImage3x(
                'assets/images/interview_room_bg.webp',
                width: screenWidth,
                height: screenHeight,
                fit: BoxFit.cover,
              ),
              // 视频播放区域
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: AnimatedOpacity(
                  opacity: 1.0,
                  duration: const Duration(milliseconds: 300),
                  child:
                      validSources.isNotEmpty
                          ? DynamicVideoPlayerStack(
                            initialActiveId: "normal_video",
                            sources: validSources,
                            width: screenWidth,
                          )
                          : SizedBox.shrink(),
                ),
              ),
              // 主要内容列：聊天列表 + 底部控制栏
              Column(
                children: [
                  Expanded(child: _ChatMessagesList(chatScrollController: _chatScrollController, animTop: animTop)),
                  // 底部动态显隐控制栏
                  _AnimatedBottomBar(),
                ],
              ),
              Positioned(
                top: animTop,
                left: 0,
                right: 0,
                child: AnimatedOpacity(
                  opacity: isCreateRTCRoomSuccess ? 1.0 : 0.0,
                  duration: const Duration(milliseconds: 100),
                  child: Visibility(
                    visible: isCreateRTCRoomSuccess,
                    maintainSize: true,
                    maintainAnimation: true,
                    maintainState: true,
                    child: RepaintBoundary(
                      child: LottieBuilder.asset(
                        lottieState.assetPath,
                        controller: _lottieController,
                        width: screenWidth,
                        height: 77,
                        fit: BoxFit.fill,
                        onLoaded: (composition) {
                          _lottieController.duration = composition.duration;
                          if (lottieState.isLooping) {
                            _lottieController.repeat();
                          } else {
                            _lottieController.forward();
                          }
                        },
                      ),
                    ),
                  ),
                ),
              ),
              // 顶部操作按钮（返回、结束面试）
              _TopBarActions(statusBarHeight: statusBarHeight),
            ],
          ),
        ),
      ),
      onWillPop: () => _handleBackNavigation(context, ref),
    );
  }
}

Future<bool> _handleBackNavigation(BuildContext context, WidgetRef ref) async {
  if (!ref.watch(interviewDetailProvider).isCreateRTCRoomSuccess) {
    context.router.pop();
    return false;
  }
  final notifier = ref.read(interviewDetailProvider.notifier);
  if (ref.watch(interviewDetailProvider).isFinishInterview) {
    _routeToFeedbackGenerating(context, ref);
  } else {
    final msgList = ref.read(interviewDetailProvider).msgList; // 使用 read 获取当前状态
    final bool hasCandidateSpoken = msgList.any((msg) => msg.sender == MessageSender.candidate);
    final pageTime = notifier.seconds;
    final interviewType = notifier.interviewType == 0 ? "求职面试" : "雅思面试";
    ReportService.reportBlast("end_interview_click", {"Interview_Type": interviewType, "Interview_Time": pageTime});
    showEndInterviewDialog(context, () {
      if (hasCandidateSpoken) {
        KLog.i("InterviewDetailsPage", "用户已发言，可以结束面试并生成报告。");
        _routeToFeedbackGenerating(context, ref);
      } else {
        KLog.i("InterviewDetailsPage", "用户未发言。");
        ReportService.reportBlast("Abnormal_exit", {});
        ref.read(interviewDetailProvider.notifier).leaveRoom();
        PageUtils.navigateToHomeAndRemoveOthers(context.router);
      }
    });
  }
  return false;
}

void _routeToFeedbackGenerating(BuildContext context, WidgetRef ref) {
  ref.read(interviewDetailProvider.notifier).leaveRoom();
  final roomId = ref.read(interviewDetailProvider.notifier).roomId;
  print('面试详情roomId: ${roomId}');
  context.router.pushAndPopUntil(
    FeedbackGeneratingRoute(interviewId: roomId),
    predicate: (route) => route.settings.name == InterviewTypeChooseRoute.name,
  );
}

// --- 分离出的组件 ---

// 组件：顶部操作按钮 (返回、结束面试)
class _TopBarActions extends ConsumerWidget {
  final double statusBarHeight;

  const _TopBarActions({required this.statusBarHeight});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final provider = ref.watch(interviewDetailProvider);
    final notifier = ref.read(interviewDetailProvider.notifier);
    return Positioned(
      top: statusBarHeight + 10.0,
      left: 0,
      right: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 返回按钮 (当前逻辑是切换底部栏可见性，仅为演示)
            GestureDetector(
              onTap: () async {
                await _handleBackNavigation(context, ref);
              },
              child: Container(
                padding: const EdgeInsets.all(8.0),
                child: Image.asset('assets/images/ic_black.png', width: 24, height: 24),
              ),
            ),
            // 结束面试按钮
            GestureDetector(
              onTap: () {
                final pageTime = notifier.seconds;
                final interviewType = notifier.interviewType == 0 ? "求职面试" : "雅思面试";
                ReportService.reportBlast("end_interview_click", {
                  "Interview_Type": interviewType,
                  "Interview_Time": pageTime,
                });
                final msgList = ref.read(interviewDetailProvider).msgList; // 使用 read 获取当前状态
                final bool hasCandidateSpoken = msgList.any((msg) => msg.sender == MessageSender.candidate);
                showEndInterviewDialog(context, () {
                  if (hasCandidateSpoken) {
                    KLog.i("InterviewDetailsPage", "用户已发言，可以结束面试并生成报告。");
                    _routeToFeedbackGenerating(context, ref);
                  } else {
                    KLog.i("InterviewDetailsPage", "用户未发言。");
                    ReportService.reportBlast("Abnormal_exit", {});
                    ref.read(interviewDetailProvider.notifier).leaveRoom();
                    PageUtils.navigateToHomeAndRemoveOthers(context.router);
                  }
                });
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 11.5, vertical: 5.0),
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(255, 200, 200, 0.4),
                  borderRadius: BorderRadius.circular(15.0),
                ),
                child: const Text("结束面试", style: TextStyle(color: Color(0xFFDC4444), fontSize: 14)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 组件：聊天消息列表
class _ChatMessagesList extends ConsumerWidget {
  final ScrollController chatScrollController;
  final double animTop;

  const _ChatMessagesList({required this.chatScrollController, required this.animTop});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final providerState = ref.watch(interviewDetailProvider);
    final msgList = providerState.msgList;

    // 聊天消息滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (chatScrollController.hasClients && msgList.isNotEmpty) {
        chatScrollController.jumpTo(chatScrollController.position.maxScrollExtent);
      }
    });

    return Padding(
      padding: EdgeInsets.only(top: animTop + 57), // 为顶部视频区域留出空间
      child: ShaderMask(
        shaderCallback: (Rect bounds) {
          return LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.transparent, Colors.black.withOpacity(0.05), Colors.black, Colors.black],
            stops: const [0.0, 0.08, 0.15, 1.0],
          ).createShader(bounds);
        },
        blendMode: BlendMode.dstIn,
        child: ListView.builder(
          controller: chatScrollController,
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          itemCount: msgList.length,
          itemBuilder: (context, index) {
            final msg = msgList[index];
            Widget chatBubble;
            bool isLastItem = index == msgList.length - 1;

            if (msg.sender == MessageSender.interviewer) {
              String messageToDisplay;
              // 判断条件：
              // 1. 这条消息是列表中的最后一条消息。
              // 2. 它的文本内容 msg.text 当前是空的（表示它是预留给打字机效果的）。
              // 3. providerState.interviewerText 有内容（表示AI正在打字）。
              bool isActivelyTyping = isLastItem && msg.text.isEmpty && providerState.interviewerText.isNotEmpty;

              if (isActivelyTyping) {
                messageToDisplay = providerState.interviewerText; // 显示正在打字的内容
              } else {
                messageToDisplay = msg.text; // 显示已经固化的内容
              }
              chatBubble = LeftChatBubble(position: index, message: messageToDisplay);
            } else {
              chatBubble = RightChatBubble(position: index, message: msg.text);
            }
            if (isLastItem) {
              return Padding(padding: EdgeInsets.only(bottom: 20), child: chatBubble);
            } else {
              return chatBubble;
            }
          },
        ),
      ),
    );
  }
}

// 组件：底部动态显隐控制栏 (StatefulWidget 用于管理自身动画状态)
class _AnimatedBottomBar extends ConsumerStatefulWidget {
  const _AnimatedBottomBar();

  @override
  ConsumerState<_AnimatedBottomBar> createState() => _AnimatedBottomBarState();
}

class _AnimatedBottomBarState extends ConsumerState<_AnimatedBottomBar> {
  late ScrollController _speechTextScrollController;
  bool _shouldRenderBottomBarContent = false;
  Timer? _hideBottomBarTimer;
  bool _isAnimatingIn = false;

  // 定义底部栏的固定高度 (你需要根据你的UI实际测量或计算这个值)
  // 包含背景图的高度和可能的底部安全区域
  // 从你的 assetImage3x 调用看，是 193.5 + bottomPadding
  double get _bottomBarActualHeight {
    final bottomPadding = MediaQuery.of(context).padding.bottom;
    return 193.5 + bottomPadding;
  }

  @override
  void initState() {
    super.initState();
    _speechTextScrollController = ScrollController();
    _shouldRenderBottomBarContent = ref.read(interviewDetailProvider).isShowBottomBar;
    if (_shouldRenderBottomBarContent) {
      _isAnimatingIn = false;
    }
  }

  @override
  void dispose() {
    _speechTextScrollController.dispose();
    _hideBottomBarTimer?.cancel();
    super.dispose();
  }

  void _scrollToEndSpeechText() {
    if (_speechTextScrollController.hasClients && _speechTextScrollController.position.hasContentDimensions) {
      _speechTextScrollController.animateTo(
        _speechTextScrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 100),
        curve: Curves.easeOut,
      );
    }
  }

  Duration animationDuration = Duration(milliseconds: 200); // 统一动画时长

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final providerData = ref.watch(interviewDetailProvider);
    final isShowBottomBar = providerData.isShowBottomBar; // Provider中的“目标”可见状态
    ref.listen<bool>(interviewDetailProvider.select((p) => p.isShowBottomBar), (previousIsVisible, nextIsVisible) {
      _hideBottomBarTimer?.cancel();

      if (nextIsVisible) {
        if (!_shouldRenderBottomBarContent) {
          if (mounted) {
            setState(() {
              _shouldRenderBottomBarContent = true;
              _isAnimatingIn = true;
            });
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted && _isAnimatingIn && ref.read(interviewDetailProvider).isShowBottomBar) {
                setState(() {
                  _isAnimatingIn = false;
                });
              } else if (mounted && _isAnimatingIn && !ref.read(interviewDetailProvider).isShowBottomBar) {
                setState(() {
                  _isAnimatingIn = false;
                });
              }
            });
          }
        } else {
          if (_isAnimatingIn && mounted) {
            setState(() {
              _isAnimatingIn = false;
            });
          }
        }
      } else {
        if (mounted) {
          if (_isAnimatingIn) {
            setState(() {
              _isAnimatingIn = false;
            });
          }
        }
        if (_shouldRenderBottomBarContent) {
          _hideBottomBarTimer = Timer(animationDuration, () {
            // 使用统一的动画时长
            if (mounted && !ref.read(interviewDetailProvider).isShowBottomBar) {
              setState(() {
                _shouldRenderBottomBarContent = false;
              });
            }
          });
        }
      }
    });

    ref.listen<String>(interviewDetailProvider.select((p) => p.candidateText), (_, nextText) {
      if (isShowBottomBar && nextText.isNotEmpty && _shouldRenderBottomBarContent) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _scrollToEndSpeechText();
        });
      } else if (nextText.isEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (_speechTextScrollController.hasClients) {
            // 检查controller是否还附加到可滚动小部件
            _speechTextScrollController.jumpTo(0);
          }
        });
      }
    });
    if (isShowBottomBar &&
        ref.watch(interviewDetailProvider).candidateText.isNotEmpty &&
        _shouldRenderBottomBarContent) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToEndSpeechText();
      });
    }

    // 使用 AnimatedContainer 来平滑改变底部栏所占用的空间高度
    return AnimatedContainer(
      duration: animationDuration,
      // 使用统一的动画时长
      curve: Curves.easeInOut,
      height: isShowBottomBar ? _bottomBarActualHeight : 0.0,
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(),
      // 使用 AnimatedOpacity 包裹 OverflowBox 来实现整体的透明度动画
      child: AnimatedOpacity(
        opacity: isShowBottomBar ? 1.0 : 0.0, // 根据目标可见性控制透明度
        duration: animationDuration, // 使用统一的动画时长
        curve: Curves.easeOut, // 透明度动画曲线
        child: OverflowBox(
          minHeight: 0,
          maxHeight: _bottomBarActualHeight,
          alignment: Alignment.bottomCenter, // 内容从底部开始对齐，当高度缩小时，看起来像从底部滑出
          child: Visibility(
            // Visibility 仍然用于最终控制是否渲染，以及状态保持
            visible: _shouldRenderBottomBarContent,
            maintainState: true,
            maintainAnimation: true,
            maintainSize: false,
            child: Stack(
              children: [
                assetImage3x(
                  "assets/images/ic_bg_interview_speech.png",
                  fit: BoxFit.cover,
                  width: screenWidth,
                  height: _bottomBarActualHeight,
                ),
                _SpeechTextView(speechTextScrollController: _speechTextScrollController),
                _AnswerActionButton(
                  screenWidth: screenWidth,
                  isAnimatingIn: _isAnimatingIn, // isAnimatingIn 控制按钮的入场
                  // 按钮的出场现在更多由外部的 AnimatedOpacity 和 AnimatedContainer 高度驱动
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 组件：底部栏中的语音文字显示区域
class _SpeechTextView extends ConsumerWidget {
  final ScrollController speechTextScrollController;

  const _SpeechTextView({required this.speechTextScrollController});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Positioned(
      top: 56,
      left: 0,
      right: 0,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 35.5),
        height: 23,
        alignment: Alignment.centerLeft,
        child: ShaderMask(
          shaderCallback: (Rect bounds) {
            return LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Colors.transparent, const Color(0xFF3A428A), const Color(0xFF3A428A), Colors.transparent],
              stops: const [0.0, 0.1, 0.9, 1.0],
            ).createShader(Rect.fromLTRB(0, 0, bounds.width, bounds.height));
          },
          blendMode: BlendMode.dstIn,
          child: SingleChildScrollView(
            controller: speechTextScrollController,
            scrollDirection: Axis.horizontal,
            physics: const NeverScrollableScrollPhysics(), // 通常由外部逻辑控制滚动
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 5),
              child: Text(
                ref.watch(interviewDetailProvider).candidateText,
                style: const TextStyle(fontSize: 16, color: Color(0xFF3A428A), fontWeight: FontWeight.w500),
                maxLines: 1,
                softWrap: false,
                overflow: TextOverflow.visible,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

// 组件：底部栏中的“我回答好了”按钮
class _AnswerActionButton extends ConsumerWidget {
  final double screenWidth;
  final bool isAnimatingIn; // 从父组件接收的入场动画状态

  const _AnswerActionButton({required this.screenWidth, required this.isAnimatingIn});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final providerData = ref.watch(interviewDetailProvider);
    final isShowAnswerBtn = providerData.isShowAnswerBtn;
    final isShowBottomBar = providerData.isShowBottomBar;
    final isAISpeedSay = providerData.isAISpeedSay;
    print("isShowBottomBar = $isShowBottomBar isShowAnswerBtn = $isShowAnswerBtn isAISpeedSay=$isAISpeedSay");
    return AnimatedPositioned(
      duration: const Duration(milliseconds: 1000),
      curve: Curves.elasticOut,
      width: 200,
      height: 45,
      // 按钮的 bottom 位置由 isAnimatingIn (当前是否处于入场动画第一阶段) 和 isBottomBarVisible (最终目标是否可见) 共同决定
      bottom:
          isAnimatingIn
              ? -100 // 入场动画开始时，在屏幕外
              : (isShowBottomBar
                  ? 54 // 最终显示位置
                  : -100 // 隐藏或出场动画结束位置
                  ),
      left: (screenWidth - 160) / 2,
      child: AnimatedOpacity(
        duration: const Duration(milliseconds: 250),
        // 透明度同样由 isAnimatingIn 和 isBottomBarVisible 控制
        opacity:
            isAnimatingIn
                ? 0.0 // 入场动画开始时，完全透明
                : (isShowBottomBar
                    ? 1.0 // 最终显示状态，完全不透明
                    : 0.0 // 隐藏或出场动画结束状态，完全透明
                    ),
        child: _answerActionWidget(ref, isAISpeedSay, isShowAnswerBtn),
      ),
    );
  }

  Widget? _answerActionWidget(WidgetRef ref, bool isAISpeedSay, bool isShowAnswerBtn) {
    if (isAISpeedSay) {
      return SizedBox.shrink();
    }
    if (isShowAnswerBtn) {
      return Container(
        // “我回答好了”按钮
        width: 160,
        height: 45,
        margin: const EdgeInsets.only(right: 40.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(45 / 2),
          boxShadow: [BoxShadow(color: Color(0x0F000000), blurRadius: 2, spreadRadius: 0)],
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: () {
              final notifier = ref.read(interviewDetailProvider.notifier);
              notifier.userFinishedAnswering();
            },
            borderRadius: BorderRadius.circular(160 / 2),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.multitrack_audio_rounded, color: Colors.teal[400], size: 20),
                const SizedBox(width: 6),
                const Text("我回答好了", style: TextStyle(fontSize: 16, color: Colors.black87, fontWeight: FontWeight.bold)),
              ],
            ),
          ),
        ),
      );
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Lottie.asset(
          'assets/json/mic_talk.json',
          width: 25,
          height: 23,
          fit: BoxFit.fill,
          repeat: true,
          reverse: false,
        ),
        SizedBox(width: 10),
        Expanded(
          child: Text("请对着麦克风回答", style: TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.bold)),
        ),
      ],
    );
  }
}
